package xin.shaozeming.base.common.servlet.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xin.shaozeming.base.common.Response;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: 邵泽铭
 * @date: 2018/10/22
 * @description:
 **/
@Log4j2
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{

        /**
         * 添加拦截器
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new CrossInterceptor());
            registry.addInterceptor(new DecryptInterceptor());
            registry.addInterceptor(new TokenInterceptor());
            registry.addInterceptor(new PermissionInterceptor());

        }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new  StringToEnumConverterFactory());
    }

    public static   void returnResponse(HttpServletResponse response, Response rs) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSONObject.toJSONString(rs));

        } catch (IOException e) {
            log.error(" 拦截器 response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}